export const setMeshImageToJSON = (scene) => {
   return new Promise((resolve, reject) => {
        let _json = scene.toJSON();
        console.log(_json)
        scene.traverse((mesh) => {
            if (
                mesh.material &&
                mesh.material?.map &&
                mesh.material?.map.image
            ) {
                if (mesh.material.map.image.currentSrc) {
                    textureMapUrl = mesh.material.map.image.currentSrc;
                } else {
                    const _uuid = mesh.material.uuid;
                    let _texture = _json.materials.find(
                        (v) => v.uuid === _uuid
                    );
                    if (!_texture) return;
                    let _list = ["map", "metalnessMap", "roughnessMap"];
                    _list.forEach((key) => {
                        if (_texture[key]) {
                            let _image = _json.textures.find(
                                (v) => v.uuid === _texture[key]
                            );
                            _json.images &&
                                _json.images.length &&
                                _json.images.map((v) => {
                                    if (_image.image === v.uuid && !v.url) {
                                        v.url = mesh.material.map.image;
                                    }
                                    return v;
                                });
                        }
                    });
                }
            }
        });
        resolve(_json);
    });
};

export const jsonDataToModel = (data) => {
    return new Promise((resolve, reject) => {
        const { images }  = data;
        if(!images || !images.length) resolve(data);
        images.map(v => {
            if(v.url) {
                const canvas = document.createElement("canvas");
                const { width, height } = v.url;
                canvas.width = width;
                canvas.height = height;
                const context = canvas.getContext("2d");
                context.drawImage(v.url, 0, 0);
                const textureMapUrl = canvas.toDataURL("image/png", 0.5);
                v.url = textureMapUrl;
            }
            return v;
        })

        resolve(data)
    })
}
